package com.taobao.api.convert;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.taobao.api.TaobaoApiException;
import com.taobao.api.model.Postage;
import com.taobao.api.util.ApiConstants;
import com.taobao.api.util.DateUtil;

/**
 * @author gaoweibin.tw
 *
 */
public class TaobaoPostageJSONConvert {
	
	/**
	 * 将返回的Json转换为Postage
	 * 
	 * @param json
	 * @return Postage
	 * @throws JSONException
	 * @throws TaobaoApiException
	 */
	public static Postage convertJsonToPostage(JSONObject json) throws JSONException,TaobaoApiException {
		Postage postage = new Postage();
		if (json.has(ApiConstants.POSTAGE_ID)) {
			postage.setPostageId(json.getString(ApiConstants.POSTAGE_ID));
		}
		if (json.has(ApiConstants.NAME)) {
			postage.setName(json.getString(ApiConstants.NAME));
		}
		if (json.has(ApiConstants.MEMO)) {
			postage.setMemo(json.getString(ApiConstants.MEMO));
		}
		try {
			if (json.has(ApiConstants.CREATED)) {

				postage.setCreated(DateUtil.strToDate(json.getString(ApiConstants.CREATED)));
			}
			if (json.has(ApiConstants.MODIFIED)) {
				postage.setModified(DateUtil.strToDate(json.getString(ApiConstants.MODIFIED)));
			}
		} catch (ParseException e) {
			throw new TaobaoApiException();
		}
		return postage;
	}
	
	/**
	 * 将返回的JsonArray转换为List<postage>
	 * 
	 * @param jsonArray
	 * @return List<Postage>
	 * @throws TaobaoApiException
	 */
	public static List<Postage> convertJsonArrayToPostageList(JSONArray jsonArray) throws TaobaoApiException {
		List<Postage> getPostageList = new ArrayList<Postage>();
		Postage postage = null;
		for (int i = 0; i < jsonArray.length(); i++) {
			try {
				postage = convertJsonToPostage(jsonArray.getJSONObject(i));
			} catch (JSONException e) {
				throw new TaobaoApiException(e);
			}
			getPostageList.add(postage);
		}
		return getPostageList;
	}
	
}
